﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using SharpObjects.Configuration;
using SharpObjects.Configuration.ConfigurationProviders;
using SharpObjects.Interfaces;
using SharpObjects.RuleEngine.RuleElements;
using SharpObjects.RuleEngine;

namespace SharpObjects.RuleEngine.Rules
{
    public class FormatRule : IXmlInitializable, IRule
    {
        public FieldElement[] Fields { get; set; }
        public PatternElement Pattern { get; set; }
        public string Output { get; set; }

        #region IInitializable Members

        public void Initialize(XmlElement initializationElement)
        {
            XmlConfigurationProvider init = new XmlConfigurationProvider(initializationElement);

            Output = init.GetString("@output");
            Fields = init.GetObjects<FieldElement>("field");
            Pattern = init.GetObject<PatternElement>("pattern");

            this.IsInitialized = true;
        }

        public bool IsInitialized { get; set; }

        #endregion

        #region IRule Members

        public void Execute(ref IRuleEngineContext ruleEngineContext, IDataProvider dataProvider)
        {
            if (Fields != null && Pattern != null && Output != null)
            {
                object[] values = new object[Fields.Length];

                for(int k = 0; k < values.Length; k++)
                {
                    values[k] = Fields[k].GetValue(ruleEngineContext, dataProvider);
                }

                string output = string.Format(Pattern.Pattern, values);

                ruleEngineContext.SetValue<string>(Output, output);
            }
        }

        #endregion
    }
}
